const db = require('../db/index')
const bcrypt = require('bcryptjs')
// 导入生产token的包
const jwt = require('jsonwebtoken')
// 导入秘钥
const config = require('../config')
/**
 * 注册处理函数
 * 
 * @param {} req 
 * @param {*} res 
 */
exports.regUser = (req, res) => {
    // 获取提交的用户信息
    const userInfo = req.body
    const sqlStr = 'select count(*) AS count from ev_users where username=?'
    db.query(sqlStr, userInfo.username, (err, result) => {
        if (err) {
            return res.cc('执行sql语句失败')
        }
        console.log('result[0]', result[0].count);
        if (result[0].count > 0) {
            return res.cc('用户名被占用，请更换其他用户名')
        }

        // 对密码进行加密
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        console.log('userInfo.password', userInfo.password)
        const insertStr = 'insert into ev_users  set ?'
        db.query(insertStr, { username: userInfo.username, password: userInfo.password }, (err, result) => {
            if (err) {
                return res.cc('插入用户失败')
            }
            if (result.affectedRows == 1) {

                return res.cc('插入用户成功', 0)

            }
        })
    })

}
/**
 * 登录处理函数
 * @param {} req 
 * @param {*} res 
 */
exports.login = (req, res) => {
    const userInfo = req.body
    const username = userInfo.username
    const selectUserSql = 'select * from ev_users where username=?'
    db.query(selectUserSql, username, (err, result) => {
        if (err) {
            return res.cc('执行查询用户sql语句失败')
        }
        if (result.length !== 1) {
            return res.cc('执行查询用户sql语句失败,multi user or no user')
        }
        // 用户名校验成功
        const password = userInfo.password
        const compareResult = bcrypt.compareSync(password, result[0].password)
        if (!compareResult) {
            return res.cc('密码不正确')
        }
        console.log(result[0])
        // es6高级语法，将result[0]里面的数据展开，然后将对应的字段设为空串
        const user = { ...result[0], password: '', user_pic: "" }
        console.log('user', user)
        // 生成token

        const token=jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expireIn })
        // const token=jwt.sign({
        //     exp: Math.floor(Date.now() / 1000) + (60 * 60),
        //     data: user
        //   }, config.jwtSecretKey);
        return res.send({
            status:0,
            message:"登录成功",
            token
        })
    })

}